package com.cfswt.tasksystem.controller;

import com.cfswt.tasksystem.mapper.RecordSummaryMapper;
import com.cfswt.tasksystem.mapper.RecordsMapper;
import com.cfswt.tasksystem.pojo.entity.Record;
import com.cfswt.tasksystem.pojo.entity.RecordSummary;
import com.cfswt.tasksystem.pojo.vo.RecordSummaryVO;
import com.cfswt.tasksystem.pojo.vo.RecordVO;
import com.cfswt.tasksystem.response.JsonResult;
import com.cfswt.tasksystem.security.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/record")
public class RecordController {
    @Autowired
    private RecordsMapper recordsMapper;
    @Autowired
    private RecordSummaryMapper recordSummaryMapper;

    @PostMapping("/add")
    public JsonResult addRecord(@RequestBody Record record,
                                @AuthenticationPrincipal CustomUserDetails userDetails){
        record.setUserName(userDetails.getUsername());
        recordsMapper.addRecord(record);
        Integer id = record.getId();
        List<RecordSummary> recordSummaries = record.getRecordSummaries();
        for (RecordSummary recordSummary : recordSummaries) {
            recordSummary.setRecordId(id);
            recordSummaryMapper.addRecordSummary(recordSummary);
        }
        return JsonResult.ok(record);
    }
    @GetMapping("{demandId}")
    public JsonResult selectRecordByDemandId(@PathVariable String demandId){
        List<RecordVO> recordsVO = recordsMapper.selectRecordsVOByDemandId(demandId);
        for (RecordVO recordVO : recordsVO) {
            List<RecordSummaryVO> recordSummaries = recordSummaryMapper.selectRecordSummaryVOByRecordID(recordVO.getId());
            recordVO.setRecordSummaries(recordSummaries);
        }
        System.out.println(recordsVO);
        return JsonResult.ok(recordsVO);
    }
}
